const nodemailer = require("nodemailer")
const config = require("../config")

const { findStudentById } = require("../persistent_api/studentApi")

const  log4j = require("log4js")
const logger = log4j.getLogger();

module.exports = (moduleName = "",update) => {
   return async (req,res) => {
         try{
            let callName = "";
            let id,name,email;
            const body = req.body;
            if(moduleName?.trim() === "student"){
                callName = "同学"
                id = body.studentNo;
                name = body.studentName;
                email = body.studentEmail;
            }else if(moduleName?.trim() === "teacher") {
                callName = "老师"
                id = body.teacherNo;
                name = body.teacherName;
                email = body.teacherEmail;
            }
            let transporter = nodemailer.createTransport({
                host: config.emailServer,
                port: 465,
                secure: true,
                auth: {
                    user: config.sendEmailUser,
                    pass: config.emailPass, // 签发的密匙
                }
            });
            if(update === "update"){
                const stu = (await findStudentById(body._id))[0];
                email = stu.studentEmail;
                id = stu.studentNo;
                name = stu.studentName;
            }
            console.log("发送邮件",callName+`信息${update === 'update' ? '修改' : '添加'}成功通知`);
            return await transporter.sendMail({
                from: '全栈后台管理教务系统通知 <'+config.sendEmailUser+'>', // sender address
                to: email, // list of receivers
                subject: callName+`信息${update === 'update' ? '修改' : '添加'}成功通知`, // Subject line
                html: `<b> 亲爱的： <i>${name}</i> 您的信息已在本校教务系统注册完毕 可以使用 ${callName === '同学' ? '学号' : '工号'}为 ${id} 与 姓名为 ${name} 的组合进行登录，您的注册邮箱为：${email} </b>`,
            });
         }catch(error){
              logger.error(req.ip + " - " + req.method + " - " + req.originalUrl + " - 发送邮件失败" + "-" + error.message)
         }
 }
}